package com.example.controller;

import com.example.service.IdGeneratorService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ID生成测试控制器
 */
@RestController
@RequestMapping("/test-id")
public class TestIdController {

    @Resource
    private IdGeneratorService idGeneratorService;

    /**
     * 测试ID生成
     */
    @GetMapping("/generate-id")
    public Map<String, Object> generateId(@RequestParam(defaultValue = "10") int count) {
        Map<String, Object> result = new HashMap<>();
        List<Map<String, Object>> ids = new ArrayList<>();
        
        for (int i = 0; i < count; i++) {
            Long id = idGeneratorService.nextId();
            Map<String, Object> idInfo = new HashMap<>();
            idInfo.put("id", id);
            idInfo.put("length", String.valueOf(id).length());
            idInfo.put("isOdd", id % 2 == 1);
            idInfo.put("targetDB", id % 2 == 1 ? "ds-a" : "ds-b");
            ids.add(idInfo);
        }
        
        result.put("success", true);
        result.put("data", ids);
        result.put("count", count);
        
        return result;
    }

    /**
     * 测试分片规则
     */
    @GetMapping("/sharding-rule")
    public Map<String, Object> testShardingRule() {
        Map<String, Object> result = new HashMap<>();
        
        // 生成一些测试ID
        List<Map<String, Object>> testCases = new ArrayList<>();
        for (int i = 0; i < 20; i++) {
            Long id = idGeneratorService.nextId();
            Map<String, Object> testCase = new HashMap<>();
            testCase.put("id", id);
            testCase.put("isOdd", id % 2 == 1);
            testCase.put("targetDB", id % 2 == 1 ? "ds-a" : "ds-b");
            testCases.add(testCase);
        }
        
        // 统计分布情况
        long dsACount = testCases.stream().mapToLong(tc -> 
            "ds-a".equals(tc.get("targetDB")) ? 1 : 0).sum();
        long dsBCount = testCases.stream().mapToLong(tc -> 
            "ds-b".equals(tc.get("targetDB")) ? 1 : 0).sum();
        
        Map<String, Object> statistics = new HashMap<>();
        statistics.put("ds-a", dsACount);
        statistics.put("ds-b", dsBCount);
        statistics.put("total", testCases.size());
        
        result.put("success", true);
        result.put("testCases", testCases);
        result.put("statistics", statistics);
        
        return result;
    }
} 